
const buildCss = require('antd-merge-less');
const rimraf = require('rimraf')
const fs = require('fs')
const path = require('path')
const winPath = require('slash2');
const defaultTheme = require('./defaultTheme');
const { existsSync, mkdirSync } = fs;
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);

let options = defaultTheme;

const outputPath = winPath(resolveApp('build/themes'));//输出目录
const themeTemp = winPath(resolveApp('.plugin-theme'));//dev使用临时文件目录

// 自定义webpack插件
class AntdThemeWebpackPlugin {
    constructor(options) {
        this.options = options
    }
    apply(compiler) {
        const env = process.env.NODE_ENV;
        if (env === 'development') {
            console.log(env, 'development环境暂不支持切换主题')
        } else {
            //生产环境打包主题
            compiler.hooks.afterEmit.tap(
                'AntdThemeWebpackPlugin',
                () => {
                    console.info('💄  build theme');
                    try {
                        if (existsSync(outputPath)) {
                            rimraf.sync(outputPath);
                        }
                        mkdirSync(outputPath);
                    } catch (error) {
                        // console.log(error);
                    }
                    buildCss(
                        winPath(resolveApp('src')),
                        options.theme.map(
                            (theme) => ({
                                ...theme,
                                fileName: winPath(path.join(outputPath, theme.fileName)),
                            }),
                            {
                                min: true,
                                ...options,
                            },
                        ),
                    )
                        .then(() => {
                            console.log('🎊  build theme success');
                        })
                        .catch((e) => {
                            console.log(e);
                        });
                })
        }

    }
}

module.exports = AntdThemeWebpackPlugin